package com.qnkf.util;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.util.Base64;

/**
 * @author Administrator
 */
public class Base64Util {

    /***
     * encode by Base64
     */
    public static String encodeBase64(byte[]input) throws Exception{
        Class clazz=Class.forName("com.sun.org.apache.xerces.internal.impl.dv.util.Base64");
        Method mainMethod= clazz.getMethod("encode", byte[].class);
        mainMethod.setAccessible(true);
        Object retObj=mainMethod.invoke(null, new Object[]{input});
        return (String)retObj;
    }
    /***
     * decode by Base64
     */
    public static byte[] decodeBase64(String input) throws Exception{
        Class clazz=Class.forName("com.sun.org.apache.xerces.internal.impl.dv.util.Base64");
        Method mainMethod= clazz.getMethod("decode", String.class);
        mainMethod.setAccessible(true);
        Object retObj=mainMethod.invoke(null, input);
        return (byte[])retObj;
    }

    /**
     * 判断是否是base64加密了
     * @param str
     * @return
     */
    public static boolean isBase64(String str) {
        if (str == null || str.trim().length() == 0) {
            return false;
        } else {
            if (str.length() % 4 != 0) {
                return false;
            }

            char[] strChars = str.toCharArray();
            for (char c:strChars) {
                if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9')
                        || c == '+' || c == '/' || c == '=') {
                    continue;
                } else {
                    return false;
                }
            }
            return true;
        }
    }

    /**
     * base64 解密
     * @param content
     * @return
     */
    public static String base64ToString(String content) throws UnsupportedEncodingException {
        return new String(org.apache.commons.codec.binary.Base64.decodeBase64(content),"utf-8");
    }

    /**
     * Base64加密
     * @return
     */
    public static String stringToBase64(String content){
        return new String(Base64.getEncoder().encode(content.getBytes()));
    }
}
